package edu.univercidade.tcc.server.service;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import edu.univercidade.tcc.server.config.Messages;
import edu.univercidade.tcc.server.model.ProjectMember;
import edu.univercidade.tcc.util.CryptoUtil;

public class ProjectMemberServiceImpl implements ProjectMemberService {

	@PersistenceContext
	private transient EntityManager entityManager;

	public String getPassWord(ProjectMember member) {
		return entityManager
				.createNativeQuery(
						"SELECT hashed_password FROM project_member WHERE id = :id")
				.setParameter("id", member.getId()).getSingleResult()
				.toString();
	}

	public ProjectMember getUserByLogin(String login) {
		return (ProjectMember) entityManager
				.createQuery(
						"SELECT p FROM ProjectMember p WHERE p.login = :login")
				.setParameter("login", login).getSingleResult();
	}

	public void saveProjectMember(ProjectMember projectMember) {
		projectMember.setCreatedOn(new Date());
		projectMember.setLastLoginOn(null);
		projectMember.setHashedPassword(CryptoUtil.hexaSHA256(Messages
				.getString("Application.defaultPassword")));
		projectMemberDAO.save(projectMember);
	}

	public ProjectMember updateProjectMember(ProjectMember projectMember) {
		ProjectMember persisted = projectMemberDAO.findOne(projectMember
				.getId());
		if (persisted == null) {
			persisted = projectMemberDAO.save(projectMember);
		} else {
			persisted.setFirstname(projectMember.getFirstname());
			persisted.setLastname(projectMember.getLastname());
			persisted.setLogin(projectMember.getLogin());
			persisted.setMail(projectMember.getMail());
			persisted.setMailNotification(projectMember.getMailNotification());
			persisted.setStatus(projectMember.getStatus());
			persisted = projectMemberDAO.save(persisted);
		}
		return persisted;
	}

	public void loggedProjectMember(ProjectMember projectMember) {
		ProjectMember persisted = projectMemberDAO.findOne(projectMember
				.getId());
		persisted.setLastLoginOn(projectMember.getLastLoginOn());
		persisted = projectMemberDAO.save(persisted);
	}

	@Override
	public void updatePassword(ProjectMember projectMember) {
		ProjectMember persisted = projectMemberDAO.findOne(projectMember
				.getId());
		persisted.setHashedPassword(CryptoUtil.hexaSHA256(projectMember
				.getHashedPassword()));
		projectMemberDAO.save(persisted);
	}
}
